"""
历史记录数据模型
"""

from typing import Dict, Any, Optional, List
from datetime import datetime, timedelta
from .base import BaseModel


class History(BaseModel):
    """历史记录模型类"""
    
    # 操作类型常量
    ACTION_UPLOAD = 'upload'
    ACTION_CONVERT = 'convert'
    ACTION_DOWNLOAD = 'download'
    ACTION_DELETE = 'delete'
    ACTION_SHARE = 'share'
    ACTION_TEMPLATE_USE = 'template_use'
    
    # 记录状态常量
    STATUS_SUCCESS = 'success'
    STATUS_FAILED = 'failed'
    STATUS_CANCELLED = 'cancelled'
    
    def __init__(self):
        super().__init__('history')
    
    def create_record(self, record_data: Dict[str, Any]) -> str:
        """
        创建历史记录
        
        Args:
            record_data: 记录数据
            
        Returns:
            str: 记录ID
        """
        # 生成记录ID
        record_id = self.generate_id()
        
        # 构建历史记录
        history_record = {
            'record_id': record_id,
            'user_id': record_data.get('user_id'),
            'task_id': record_data.get('task_id'),
            'action': record_data.get('action'),
            'status': record_data.get('status', self.STATUS_SUCCESS),
            'filename': record_data.get('filename'),
            'file_size': record_data.get('file_size', 0),
            'output_format': record_data.get('output_format'),
            'template_id': record_data.get('template_id'),
            'template_name': record_data.get('template_name'),
            'duration': record_data.get('duration', 0),  # 执行时间（秒）
            'quality_score': record_data.get('quality_score'),
            'error_message': record_data.get('error_message'),
            'ip_address': record_data.get('ip_address'),
            'user_agent': record_data.get('user_agent'),
            'metadata': record_data.get('metadata', {})
        }
        
        # 验证必填字段
        if not history_record['action']:
            raise ValueError("操作类型不能为空")
        
        # 创建记录
        self.create(history_record)
        return record_id
    
    def get_record(self, record_id: str) -> Optional[Dict[str, Any]]:
        """
        获取历史记录
        
        Args:
            record_id: 记录ID
            
        Returns:
            Optional[Dict]: 历史记录或None
        """
        return self.find_one({'record_id': record_id})
    
    def get_user_history(self, user_id: str, action: str = None,
                        days: int = 30, limit: int = 100, 
                        skip: int = 0) -> List[Dict[str, Any]]:
        """
        获取用户历史记录
        
        Args:
            user_id: 用户ID
            action: 操作类型过滤（可选）
            days: 查询天数
            limit: 限制数量
            skip: 跳过数量
            
        Returns:
            List[Dict]: 历史记录列表
        """
        # 计算时间范围
        start_time = self.get_current_time() - timedelta(days=days)
        
        query = {
            'user_id': user_id,
            'created_at': {'$gte': start_time}
        }
        
        if action:
            query['action'] = action
        
        return self.find_many(
            query=query,
            sort=[('created_at', -1)],
            limit=limit,
            skip=skip
        )
    
    def get_task_history(self, task_id: str) -> List[Dict[str, Any]]:
        """
        获取任务相关的历史记录
        
        Args:
            task_id: 任务ID
            
        Returns:
            List[Dict]: 历史记录列表
        """
        return self.find_many(
            query={'task_id': task_id},
            sort=[('created_at', 1)]
        )
    
    def record_upload(self, user_id: str, filename: str, file_size: int,
                     ip_address: str = None, user_agent: str = None) -> str:
        """
        记录文件上传
        
        Args:
            user_id: 用户ID
            filename: 文件名
            file_size: 文件大小
            ip_address: IP地址
            user_agent: 用户代理
            
        Returns:
            str: 记录ID
        """
        return self.create_record({
            'user_id': user_id,
            'action': self.ACTION_UPLOAD,
            'filename': filename,
            'file_size': file_size,
            'ip_address': ip_address,
            'user_agent': user_agent
        })
    
    def record_conversion(self, user_id: str, task_id: str, filename: str,
                         output_format: str, template_id: str = None,
                         template_name: str = None, duration: int = 0,
                         quality_score: int = None, status: str = None,
                         error_message: str = None) -> str:
        """
        记录文档转换
        
        Args:
            user_id: 用户ID
            task_id: 任务ID
            filename: 文件名
            output_format: 输出格式
            template_id: 模板ID
            template_name: 模板名称
            duration: 转换时间
            quality_score: 质量评分
            status: 转换状态
            error_message: 错误信息
            
        Returns:
            str: 记录ID
        """
        return self.create_record({
            'user_id': user_id,
            'task_id': task_id,
            'action': self.ACTION_CONVERT,
            'filename': filename,
            'output_format': output_format,
            'template_id': template_id,
            'template_name': template_name,
            'duration': duration,
            'quality_score': quality_score,
            'status': status or self.STATUS_SUCCESS,
            'error_message': error_message
        })
    
    def record_download(self, user_id: str, task_id: str, filename: str,
                       ip_address: str = None) -> str:
        """
        记录文件下载
        
        Args:
            user_id: 用户ID
            task_id: 任务ID
            filename: 文件名
            ip_address: IP地址
            
        Returns:
            str: 记录ID
        """
        return self.create_record({
            'user_id': user_id,
            'task_id': task_id,
            'action': self.ACTION_DOWNLOAD,
            'filename': filename,
            'ip_address': ip_address
        })
    
    def record_template_usage(self, user_id: str, template_id: str,
                            template_name: str, task_id: str = None) -> str:
        """
        记录模板使用
        
        Args:
            user_id: 用户ID
            template_id: 模板ID
            template_name: 模板名称
            task_id: 任务ID
            
        Returns:
            str: 记录ID
        """
        return self.create_record({
            'user_id': user_id,
            'task_id': task_id,
            'action': self.ACTION_TEMPLATE_USE,
            'template_id': template_id,
            'template_name': template_name
        })
    
    def get_user_statistics(self, user_id: str, days: int = 30) -> Dict[str, Any]:
        """
        获取用户统计信息
        
        Args:
            user_id: 用户ID
            days: 统计天数
            
        Returns:
            Dict: 统计信息
        """
        start_time = self.get_current_time() - timedelta(days=days)
        base_query = {
            'user_id': user_id,
            'created_at': {'$gte': start_time}
        }
        
        # 统计各类操作数量
        stats = {
            'total_actions': self.count(base_query),
            'uploads': self.count({**base_query, 'action': self.ACTION_UPLOAD}),
            'conversions': self.count({**base_query, 'action': self.ACTION_CONVERT}),
            'downloads': self.count({**base_query, 'action': self.ACTION_DOWNLOAD}),
            'successful_conversions': self.count({
                **base_query,
                'action': self.ACTION_CONVERT,
                'status': self.STATUS_SUCCESS
            }),
            'failed_conversions': self.count({
                **base_query,
                'action': self.ACTION_CONVERT,
                'status': self.STATUS_FAILED
            })
        }
        
        # 计算成功率
        if stats['conversions'] > 0:
            stats['success_rate'] = round(
                (stats['successful_conversions'] / stats['conversions']) * 100, 2
            )
        else:
            stats['success_rate'] = 0
        
        # 获取最常用的输出格式
        stats['popular_formats'] = self._get_popular_formats(user_id, days)
        
        # 获取最常用的模板
        stats['popular_templates'] = self._get_popular_templates(user_id, days)
        
        return stats
    
    def get_system_statistics(self, days: int = 30) -> Dict[str, Any]:
        """
        获取系统统计信息
        
        Args:
            days: 统计天数
            
        Returns:
            Dict: 系统统计信息
        """
        start_time = self.get_current_time() - timedelta(days=days)
        base_query = {'created_at': {'$gte': start_time}}
        
        stats = {
            'total_actions': self.count(base_query),
            'total_uploads': self.count({**base_query, 'action': self.ACTION_UPLOAD}),
            'total_conversions': self.count({**base_query, 'action': self.ACTION_CONVERT}),
            'total_downloads': self.count({**base_query, 'action': self.ACTION_DOWNLOAD}),
            'successful_conversions': self.count({
                **base_query,
                'action': self.ACTION_CONVERT,
                'status': self.STATUS_SUCCESS
            }),
            'failed_conversions': self.count({
                **base_query,
                'action': self.ACTION_CONVERT,
                'status': self.STATUS_FAILED
            }),
            'active_users': len(self._get_active_users(days)),
            'popular_formats': self._get_popular_formats(None, days),
            'popular_templates': self._get_popular_templates(None, days)
        }
        
        # 计算系统成功率
        if stats['total_conversions'] > 0:
            stats['system_success_rate'] = round(
                (stats['successful_conversions'] / stats['total_conversions']) * 100, 2
            )
        else:
            stats['system_success_rate'] = 0
        
        return stats
    
    def cleanup_old_records(self, days: int = 90) -> int:
        """
        清理旧的历史记录
        
        Args:
            days: 保留天数
            
        Returns:
            int: 清理的记录数量
        """
        cutoff_time = self.get_current_time() - timedelta(days=days)
        
        query = {'created_at': {'$lt': cutoff_time}}
        return self.delete_many(query)
    
    def _get_popular_formats(self, user_id: str = None, days: int = 30) -> List[Dict[str, Any]]:
        """
        获取热门输出格式
        
        Args:
            user_id: 用户ID（可选）
            days: 统计天数
            
        Returns:
            List[Dict]: 格式统计列表
        """
        start_time = self.get_current_time() - timedelta(days=days)
        match_query = {
            'action': self.ACTION_CONVERT,
            'created_at': {'$gte': start_time},
            'output_format': {'$ne': None}
        }
        
        if user_id:
            match_query['user_id'] = user_id
        
        pipeline = [
            {'$match': match_query},
            {'$group': {
                '_id': '$output_format',
                'count': {'$sum': 1}
            }},
            {'$sort': {'count': -1}},
            {'$limit': 10}
        ]
        
        results = list(self.collection.aggregate(pipeline))
        return [{'format': r['_id'], 'count': r['count']} for r in results]
    
    def _get_popular_templates(self, user_id: str = None, days: int = 30) -> List[Dict[str, Any]]:
        """
        获取热门模板
        
        Args:
            user_id: 用户ID（可选）
            days: 统计天数
            
        Returns:
            List[Dict]: 模板统计列表
        """
        start_time = self.get_current_time() - timedelta(days=days)
        match_query = {
            'action': self.ACTION_TEMPLATE_USE,
            'created_at': {'$gte': start_time},
            'template_id': {'$ne': None}
        }
        
        if user_id:
            match_query['user_id'] = user_id
        
        pipeline = [
            {'$match': match_query},
            {'$group': {
                '_id': '$template_id',
                'template_name': {'$first': '$template_name'},
                'count': {'$sum': 1}
            }},
            {'$sort': {'count': -1}},
            {'$limit': 10}
        ]
        
        results = list(self.collection.aggregate(pipeline))
        return [{
            'template_id': r['_id'],
            'template_name': r['template_name'],
            'count': r['count']
        } for r in results]
    
    def _get_active_users(self, days: int = 30) -> List[str]:
        """
        获取活跃用户列表
        
        Args:
            days: 统计天数
            
        Returns:
            List[str]: 活跃用户ID列表
        """
        start_time = self.get_current_time() - timedelta(days=days)
        
        pipeline = [
            {'$match': {
                'created_at': {'$gte': start_time},
                'user_id': {'$ne': None}
            }},
            {'$group': {'_id': '$user_id'}},
            {'$project': {'user_id': '$_id'}}
        ]
        
        results = list(self.collection.aggregate(pipeline))
        return [r['user_id'] for r in results]